<template>
  <van-list error-text="请求失败，点击重新加载" v-model:error="error" v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
    <div class="list">
       <slot name="son" :son="list"></slot>
    </div>
  </van-list>
</template>

<script lang="ts" setup>
import { ref, defineProps, watch, onActivated } from 'vue'
import { GetHomeGoods } from '@/api/home'
import { GetCategoryGoods } from '@/api/category'
import { UserCollect } from '@/api/mine'
import { CollectNum } from '@/pinia'
import { storeToRefs } from 'pinia'

const store = CollectNum()
const { saveCollect } = CollectNum()
const { collectNum } = storeToRefs(store)
const list = ref([]) // 数据列表
const loading = ref(false)
const finished = ref(false)
const pageCurrent = ref(1)
const error = ref(false)
const collectProductNum = ref(0) // 我的收藏产品的数量

const props = defineProps({
  page: { type: String, required: true },
  typeList: { type: String },
  cid: { type: Number }
})

// 加载更多列表 数据初始化
const init = async (cid?: number | undefined) => {
  let res = null
  if (props.page === 'home') { // home页面的数据
    res = await GetHomeGoods(props.typeList, pageCurrent.value).catch(() => {
      loading.value = false
      error.value = true
    })
  } else if (props.page === 'category') { // 分类页面
    res = await GetCategoryGoods(props.typeList, cid, pageCurrent.value).catch(() => {
      loading.value = false
      error.value = true
    })
  } else { // collect页面
    res = await UserCollect(pageCurrent.value).catch(() => {
      loading.value = false
      error.value = true
    })
  }

  try {
    if (res?.status === 200) {
      pageCurrent.value++
      loading.value = false
      finished.value = false
      if (props.page === 'collect') {
        collectProductNum.value = res.data.data.length
        saveCollect(res.data.data.length)
        list.value = list.value.concat(res.data.data) // 追加数据到列表中
        if (res.data.data.length < 10 || res.data.data.length === 0) {
          finished.value = true
        }
      } else {
        list.value = list.value.concat(res.data.goods.data)
        if (res.data.goods.data.length < 10 || res.data.goods.data.length === 0) {
          finished.value = true
        }
      }
    }
  } catch (error) {
    loading.value = false
  }
}

const onLoad = () => {
  init(props.cid)
}

// 分类页面 点击左侧的sliderbar  右侧显示不同的内容
watch(() => props.cid, (newValue) => {
  list.value = []
  pageCurrent.value = 1
  init(newValue)
})

// 收藏页面
onActivated(() => {
  if (props.page === 'collect' && collectNum.value !== collectProductNum.value) {
    pageCurrent.value = 1
    list.value = []
    init(pageCurrent.value)
  }
})

</script>
